import os
from uuid import UUID

from PyQt5.QtWidgets import QVBoxLayout, QWidget, QTreeView, QAbstractItemView
from PyQt5.QtCore import Qt, QModelIndex
from PyQt5.QtGui import QStandardItemModel, QIcon, QPixmap

from data import database, get_cover

from player.dialogs.editors.cover import CoverEditor

class CoverList(QWidget):
    COVER_NAME, COVER_UUID = range(2)

    def __init__(self):
        super().__init__(None)

        layout = QVBoxLayout()

        self.cover_list = QTreeView()
        self.cover_list.doubleClicked.connect(self.cover_list_double_clicked)
        self.cover_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.cover_list_model = QStandardItemModel(0, 2, self)
        self.cover_list.setModel(self.cover_list_model)
        self.cover_list_model.setHeaderData(self.COVER_NAME, Qt.Horizontal, "Name")
        self.cover_list_model.setHeaderData(self.COVER_UUID, Qt.Horizontal, "UUID")
        layout.addWidget(self.cover_list)
        self.refresh_cover_list()

        self.setLayout(layout)

    def refresh_cover_list(self):
        self.cover_list_model.removeRows(0, self.cover_list_model.rowCount())
        for uuid in sorted(database['covers'], key=lambda x: str(database['covers'][x]['name']) if database['covers'][x]['name'] else 'Unknown', reverse=True):
            self.cover_list_model.insertRow(0)
            self.cover_list_model.itemFromIndex(self.cover_list_model.index(0, 0)).setIcon(QIcon(get_cover(uuid)))
            self.cover_list_model.setData(self.cover_list_model.index(0, self.COVER_NAME), database['covers'][uuid]['name'] if database['covers'][uuid]['name'] else 'Unknown')
            self.cover_list_model.setData(self.cover_list_model.index(0, self.COVER_UUID), str(uuid))

        self.cover_list.resizeColumnToContents(self.COVER_NAME)
        self.cover_list.resizeColumnToContents(self.COVER_UUID)

    def uuid_from_index(self, index: QModelIndex) -> UUID:
        index = self.cover_list_model.index(index.row(), self.COVER_UUID)
        item = self.cover_list_model.itemFromIndex(index)
        uuid = item.text()
        return UUID(uuid)

    def cover_list_double_clicked(self, index: QModelIndex):
        uuid = self.uuid_from_index(index)
        editor = CoverEditor(uuid)
        editor.exec_()
        self.refresh_cover_list()
